<template>
    <div class="uploardBox">
        <div>头像</div>
        <div v-if="isHave" class="imgBox" @click="handleUpload">
            <img v-if="imgUrl" :src="imgUrl">
        </div>
        <div v-else class="cameraBox" @click="handleUpload">
            <img width="20" height="20" src="@/assets/images/camera.png">
        </div>
    </div>
</template>

<script>
    import { uploadAttach, queryFileInfo } from '@/api/common';
    import { modifyUserInfo } from '@/api/platframe/mainFrame/mine';
    export default {
        model: {
            prop: 'pValue',  // 接受父值，用于显示
            event: 'eValue', // 传给父的标记
        },
        props: {
            pValue: {
                type: String,
			    default: ''
            },
        },
        components: {

        },
        data () {
            return {
                accept: '.png,.jpg,.jpeg',
                // 文件最大：50M
                maxSize: 51200,
                isHave: false, // false没有头像
                imgUrl: '',
            };
        },
        mounted () {},
        watch: {
            pValue: {
                handler(val) {
                    if (val) {
                        this.isHave = true;
                        let obj = {
                            "fileCode": val,
                            "height": 60,
                            "width": 60
                        }
                        queryFileInfo(obj).then(res => {
                            this.imgUrl = res.data.url;
                        })
                    }
                }
            }
        },
        methods: {
            // 上传头像
            handleUpload() {
                let _this = this;
                wx.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    quality: 0.5, //压缩质量，范围0～1，数值越小，质量越低，压缩率越高（仅对jpg有效）
                    success: function (res) {
                        var localIds = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        let fileName = localIds.slice(localIds.lastIndexOf("/") + 1);
                        let type = fileName.slice(fileName.lastIndexOf(".") + 1);
                        wx.getLocalImgData({
                            localId: localIds,
                            success: function (source) {
                                if (source.localData) {
                                    _this.getFileFrombase64(source.localData, fileName, type);
                                }
                            }
                        });
                    }
                });
            
            },
            // 将base64转为file对象
            getFileFrombase64 (data, fileName, type) {
                const dataArr = data.split(",");
                const byteString = atob(dataArr[1]);
                const options = {
                    type: "image/" + (type == 'jpg' ? 'jpeg' : type),
                    endings: "native"
                }
                const u8Arr = new Uint8Array(byteString.length);
                for (let i = 0; i < byteString.length; i++) {
                    u8Arr[i] = byteString.charCodeAt(i);
                }
                let fileOfBlob = new File([u8Arr], fileName, options);
                uploadAttach(fileOfBlob).then(res => {
                    if (res.code === 1000 && res.data) {
                        this.$emit("eValue", res.data.fileCode);
                        this.preserve(res.data.fileCode);
                    }
                })
            },
            
            // 保存头像
            preserve(val) {
                let obj = {
                    'fileCode':val,
                    'staffId': sessionStorage.getItem("userid")
                    // 'staffId':'53E33C3A2D0B4E98917487B92E2586D6'
                }
                modifyUserInfo(obj).then(res=>{
                    if (res.code === 1000) {
                        this.$Notify({ type: 'success', message: '上传头像成功！' });
                    }
                });
            },
        }
    };
</script>

<style scoped lang="less">
.uploardBox {
    width: calc(~'100% - 32px');
    padding: 10px 0;
    margin: 0 16px;
    border-bottom: 1px solid #f8f8f9;

    display: flex;
    align-items: center;
    justify-content: space-between;

    .imgBox{
        width: 60px;
        height: 60px;
        >img {
            width: 60px;
            height: 60px;
            border-radius: 50%;
        }
    }

    .cameraBox {
        width: 60px;
        height: 60px;
        background-color: #f7f8fa;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>